<template>
  <div class="feature-engineering">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>特征工程</span>
          <el-button-group>
            <el-button type="primary" @click="handleImport">
              <el-icon><Upload /></el-icon>导入特征
            </el-button>
            <el-button type="success" @click="handleSave">
              <el-icon><Check /></el-icon>保存选择
            </el-button>
          </el-button-group>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 特征选择器 -->
        <el-tab-pane label="特征选择器" name="selector">
          <div class="feature-selector">
            <el-row :gutter="20">
              <!-- 可用特征列表 -->
              <el-col :span="8">
                <el-card class="feature-list">
                  <template #header>
                    <div class="card-header">
                      <span>可用特征</span>
                      <el-input
                        v-model="searchQuery"
                        placeholder="搜索特征"
                        prefix-icon="Search"
                        clearable
                      />
                    </div>
                  </template>
                  <el-checkbox-group v-model="selectedFeatures">
                    <el-checkbox
                      v-for="feature in filteredFeatures"
                      :key="feature.id"
                      :label="feature.id"
                    >
                      {{ feature.name }} ({{ feature.code }})
                    </el-checkbox>
                  </el-checkbox-group>
                </el-card>
              </el-col>

              <!-- 特征重要性分析 -->
              <el-col :span="16">
                <el-card class="feature-importance">
                  <template #header>
                    <div class="card-header">
                      <span>特征重要性分析</span>
                      <el-radio-group v-model="importanceType" size="small">
                        <el-radio-button label="correlation">相关性</el-radio-button>
                        <el-radio-button label="importance">重要性</el-radio-button>
                      </el-radio-group>
                    </div>
                  </template>
                  <div ref="importanceChartRef" class="chart-container"></div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 特征转换 -->
        <el-tab-pane label="特征转换" name="transformation">
          <div class="feature-transformation">
            <el-row :gutter="20">
              <!-- 转换规则列表 -->
              <el-col :span="8">
                <el-card class="transformation-list">
                  <template #header>
                    <div class="card-header">
                      <span>转换规则</span>
                      <el-button type="primary" @click="handleAddTransformation">
                        <el-icon><Plus /></el-icon>添加转换
                      </el-button>
                    </div>
                  </template>
                  <el-collapse v-model="activeTransformations">
                    <el-collapse-item
                      v-for="transformation in transformations"
                      :key="transformation.id"
                      :title="transformation.name"
                      :name="transformation.id"
                    >
                      <template #extra>
                        <el-tag size="small">{{ transformation.type }}</el-tag>
                      </template>
                      <p>{{ transformation.description }}</p>
                      <div class="transformation-actions">
                        <el-button-group>
                          <el-button type="primary" link @click="handleEditTransformation(transformation)">
                            编辑
                          </el-button>
                          <el-button type="danger" link @click="handleDeleteTransformation(transformation)">
                            删除
                          </el-button>
                        </el-button-group>
                      </div>
                    </el-collapse-item>
                  </el-collapse>
                </el-card>
              </el-col>

              <!-- 转换预览 -->
              <el-col :span="16">
                <el-card class="transformation-preview">
                  <template #header>
                    <div class="card-header">
                      <span>转换预览</span>
                      <el-button-group>
                        <el-button type="primary" @click="handlePreview">
                          <el-icon><Refresh /></el-icon>刷新预览
                        </el-button>
                        <el-button type="success" @click="handleApply">
                          <el-icon><Check /></el-icon>应用转换
                        </el-button>
                      </el-button-group>
                    </div>
                  </template>
                  <el-table :data="previewData" style="width: 100%">
                    <el-table-column prop="original" label="原始值" />
                    <el-table-column prop="transformed" label="转换后" />
                    <el-table-column prop="rule" label="转换规则" />
                  </el-table>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 特征版本 -->
        <el-tab-pane label="特征版本" name="version">
          <div class="feature-version">
            <el-row :gutter="20">
              <!-- 版本列表 -->
              <el-col :span="8">
                <el-card class="version-list">
                  <template #header>
                    <div class="card-header">
                      <span>版本历史</span>
                      <el-button type="primary" @click="handleCreateVersion">
                        <el-icon><Plus /></el-icon>创建版本
                      </el-button>
                    </div>
                  </template>
                  <el-timeline>
                    <el-timeline-item
                      v-for="version in versions"
                      :key="version.id"
                      :timestamp="version.time"
                      :type="version.type"
                      :hollow="version.id !== selectedVersion"
                      @click="handleSelectVersion(version)"
                    >
                      <h4>{{ version.name }}</h4>
                      <p>{{ version.description }}</p>
                    </el-timeline-item>
                  </el-timeline>
                </el-card>
              </el-col>

              <!-- 版本详情 -->
              <el-col :span="16">
                <el-card class="version-detail" v-if="selectedVersion">
                  <template #header>
                    <div class="card-header">
                      <span>版本详情</span>
                      <el-button-group>
                        <el-button type="primary" @click="handleExportVersion">
                          <el-icon><Download /></el-icon>导出
                        </el-button>
                        <el-button type="success" @click="handleDeployVersion">
                          <el-icon><Upload /></el-icon>部署
                        </el-button>
                      </el-button-group>
                    </div>
                  </template>
                  <div class="version-content">
                    <h4>特征列表</h4>
                    <el-table :data="selectedVersion.features" style="width: 100%">
                      <el-table-column prop="name" label="特征名称" />
                      <el-table-column prop="type" label="类型" />
                      <el-table-column prop="transformation" label="转换规则" />
                    </el-table>

                    <h4>版本说明</h4>
                    <p>{{ selectedVersion.description }}</p>

                    <h4>性能指标</h4>
                    <el-descriptions :column="2" border>
                      <el-descriptions-item label="特征数量">
                        {{ selectedVersion.metrics.featureCount }}
                      </el-descriptions-item>
                      <el-descriptions-item label="特征维度">
                        {{ selectedVersion.metrics.featureDimension }}
                      </el-descriptions-item>
                      <el-descriptions-item label="创建时间">
                        {{ selectedVersion.createTime }}
                      </el-descriptions-item>
                      <el-descriptions-item label="创建者">
                        {{ selectedVersion.creator }}
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加/编辑转换规则对话框 -->
    <el-dialog
      v-model="transformationDialogVisible"
      :title="transformationDialogType === 'add' ? '添加转换规则' : '编辑转换规则'"
      width="500px"
    >
      <el-form
        ref="transformationFormRef"
        :model="transformationForm"
        :rules="transformationRules"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="transformationForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="转换类型" prop="type">
          <el-select v-model="transformationForm.type" placeholder="请选择转换类型">
            <el-option label="标准化" value="standardization" />
            <el-option label="归一化" value="normalization" />
            <el-option label="对数转换" value="log" />
            <el-option label="多项式" value="polynomial" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用特征" prop="features">
          <el-select
            v-model="transformationForm.features"
            multiple
            placeholder="请选择适用特征"
          >
            <el-option
              v-for="feature in availableFeatures"
              :key="feature.id"
              :label="feature.name"
              :value="feature.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参数配置">
          <el-collapse>
            <el-collapse-item title="基础参数" name="1">
              <el-form-item label="均值">
                <el-input-number v-model="transformationForm.params.mean" :step="0.1" />
              </el-form-item>
              <el-form-item label="标准差">
                <el-input-number v-model="transformationForm.params.std" :step="0.1" :min="0" />
              </el-form-item>
            </el-collapse-item>
            <el-collapse-item title="高级参数" name="2">
              <el-form-item label="处理异常值">
                <el-switch v-model="transformationForm.params.handleOutliers" />
              </el-form-item>
              <el-form-item label="缺失值处理">
                <el-select v-model="transformationForm.params.missingValueStrategy">
                  <el-option label="均值填充" value="mean" />
                  <el-option label="中位数填充" value="median" />
                  <el-option label="删除" value="drop" />
                </el-select>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="transformationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTransformationSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 创建版本对话框 -->
    <el-dialog
      v-model="versionDialogVisible"
      title="创建新版本"
      width="500px"
    >
      <el-form
        ref="versionFormRef"
        :model="versionForm"
        :rules="versionRules"
        label-width="100px"
      >
        <el-form-item label="版本名称" prop="name">
          <el-input v-model="versionForm.name" placeholder="请输入版本名称" />
        </el-form-item>
        <el-form-item label="版本说明" prop="description">
          <el-input
            v-model="versionForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入版本说明"
          />
        </el-form-item>
        <el-form-item label="选择特征" prop="features">
          <el-transfer
            v-model="versionForm.features"
            :data="availableFeatures"
            :titles="['可选特征', '已选特征']"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="versionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleVersionSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  Upload,
  Check,
  Plus,
  Refresh,
  Download,
  Search
} from '@element-plus/icons-vue'

// 标签页
const activeTab = ref('selector')

// 特征选择器
const searchQuery = ref('')
const selectedFeatures = ref([])
const importanceType = ref('importance')
const importanceChartRef = ref(null)
let importanceChart = null

// 特征数据
const features = ref([
  { id: 1, name: '温度', code: 'temperature', importance: 0.4 },
  { id: 2, name: '湿度', code: 'humidity', importance: 0.3 },
  { id: 3, name: '压力', code: 'pressure', importance: 0.2 },
  { id: 4, name: '振动', code: 'vibration', importance: 0.1 }
])

// 过滤后的特征列表
const filteredFeatures = computed(() => {
  if (!searchQuery.value) return features.value
  const query = searchQuery.value.toLowerCase()
  return features.value.filter(feature =>
    feature.name.toLowerCase().includes(query) ||
    feature.code.toLowerCase().includes(query)
  )
})

// 特征转换
const activeTransformations = ref([])
const transformations = ref([
  {
    id: 1,
    name: '温度标准化',
    type: 'Z-score',
    description: '对温度数据进行标准化处理'
  },
  {
    id: 2,
    name: '湿度归一化',
    type: 'Min-Max',
    description: '将湿度值归一化到[0,1]区间'
  }
])

// 转换预览数据
const previewData = ref([
  { original: 25.6, transformed: 0.5, rule: '温度标准化' },
  { original: 65.3, transformed: 0.8, rule: '湿度归一化' }
])

// 特征版本
const versions = ref([
  {
    id: 1,
    name: 'v1.2.0',
    type: 'primary',
    time: '3天前',
    description: '添加振动特征',
    features: [
      { name: '温度', type: '数值型', transformation: '标准化' },
      { name: '湿度', type: '数值型', transformation: '归一化' },
      { name: '振动', type: '数值型', transformation: '原始值' }
    ],
    metrics: {
      featureCount: 3,
      featureDimension: 5
    },
    createTime: '2024-03-17 10:00:00',
    creator: 'admin'
  },
  {
    id: 2,
    name: 'v1.1.0',
    type: 'info',
    time: '1周前',
    description: '优化温度特征',
    features: [
      { name: '温度', type: '数值型', transformation: '标准化' },
      { name: '湿度', type: '数值型', transformation: '归一化' }
    ],
    metrics: {
      featureCount: 2,
      featureDimension: 4
    },
    createTime: '2024-03-10 15:30:00',
    creator: 'admin'
  }
])

const selectedVersion = ref(null)

// 对话框相关
const transformationDialogVisible = ref(false)
const transformationDialogType = ref('add')
const transformationFormRef = ref(null)
const transformationForm = reactive({
  name: '',
  type: '',
  features: [],
  params: {
    mean: 0,
    std: 1,
    handleOutliers: true,
    missingValueStrategy: 'mean'
  }
})

const transformationRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择转换类型', trigger: 'change' }
  ],
  features: [
    { required: true, message: '请选择适用特征', trigger: 'change' }
  ]
}

const versionDialogVisible = ref(false)
const versionFormRef = ref(null)
const versionForm = reactive({
  name: '',
  description: '',
  features: []
})

const versionRules = {
  name: [
    { required: true, message: '请输入版本名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入版本说明', trigger: 'blur' }
  ],
  features: [
    { required: true, message: '请选择特征', trigger: 'change' }
  ]
}

// 初始化特征重要性图表
onMounted(() => {
  importanceChart = echarts.init(importanceChartRef.value)
  updateImportanceChart()
})

// 更新特征重要性图表
const updateImportanceChart = () => {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      max: 1
    },
    yAxis: {
      type: 'category',
      data: features.value.map(f => f.name)
    },
    series: [
      {
        name: '特征重要性',
        type: 'bar',
        data: features.value.map(f => f.importance),
        itemStyle: {
          color: function(params) {
            const colorList = [
              '#36a2eb',
              '#4bc0c0',
              '#9966ff',
              '#ff9f40'
            ]
            return colorList[params.dataIndex]
          }
        }
      }
    ]
  }
  importanceChart.setOption(option)
}

// 处理函数
const handleImport = () => {
  // TODO: 实现特征导入功能
  ElMessage.success('特征导入成功')
}

const handleSave = () => {
  // TODO: 实现特征选择保存功能
  ElMessage.success('特征选择已保存')
}

const handleAddTransformation = () => {
  transformationDialogType.value = 'add'
  transformationDialogVisible.value = true
  Object.assign(transformationForm, {
    name: '',
    type: '',
    features: [],
    params: {
      mean: 0,
      std: 1,
      handleOutliers: true,
      missingValueStrategy: 'mean'
    }
  })
}

const handleEditTransformation = (transformation) => {
  transformationDialogType.value = 'edit'
  transformationDialogVisible.value = true
  Object.assign(transformationForm, transformation)
}

const handleDeleteTransformation = (transformation) => {
  ElMessageBox.confirm(
    '确定要删除该转换规则吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 实现删除功能
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handlePreview = () => {
  // TODO: 实现预览功能
  ElMessage.success('预览已更新')
}

const handleApply = () => {
  // TODO: 实现应用功能
  ElMessage.success('转换已应用')
}

const handleTransformationSubmit = async () => {
  if (!transformationFormRef.value) return
  
  await transformationFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 实现保存功能
      ElMessage.success(transformationDialogType.value === 'add' ? '创建成功' : '更新成功')
      transformationDialogVisible.value = false
    }
  })
}

const handleCreateVersion = () => {
  versionDialogVisible.value = true
  Object.assign(versionForm, {
    name: '',
    description: '',
    features: []
  })
}

const handleSelectVersion = (version) => {
  selectedVersion.value = version
}

const handleExportVersion = () => {
  // TODO: 实现导出功能
  ElMessage.success('版本导出成功')
}

const handleDeployVersion = () => {
  // TODO: 实现部署功能
  ElMessage.success('版本部署成功')
}

const handleVersionSubmit = async () => {
  if (!versionFormRef.value) return
  
  await versionFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 实现保存功能
      ElMessage.success('版本创建成功')
      versionDialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.feature-engineering {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.feature-list {
  height: 600px;
}

.feature-list :deep(.el-card__body) {
  height: calc(100% - 55px);
  overflow-y: auto;
}

.feature-importance {
  height: 600px;
}

.chart-container {
  height: 500px;
}

.transformation-list {
  height: 600px;
}

.transformation-list :deep(.el-card__body) {
  height: calc(100% - 55px);
  overflow-y: auto;
}

.transformation-preview {
  height: 600px;
}

.version-list {
  height: 600px;
}

.version-list :deep(.el-card__body) {
  height: calc(100% - 55px);
  overflow-y: auto;
}

.version-detail {
  height: 600px;
}

.version-content {
  height: calc(100% - 55px);
  overflow-y: auto;
}

.version-content h4 {
  margin: 20px 0 10px;
}

.version-content h4:first-child {
  margin-top: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

:deep(.el-collapse-item__header) {
  font-size: 14px;
  font-weight: bold;
}

:deep(.el-timeline-item__content) {
  cursor: pointer;
}

:deep(.el-timeline-item__content:hover) {
  color: var(--el-color-primary);
}
</style> 